import React from "react"
import { Drawer, Form, InputNumber, Input, Button, message } from "antd"
import { post } from "@/utils/request"

interface FormInfo {
  url: string
}

export const CreateDrawer: React.FC<{
  visible: boolean
  onClose: () => void
  onSuccess: (uuid: string) => void
}> = ({ visible, onClose, onSuccess }) => {
  const [form] = Form.useForm()

  const postCreateData = (data: FormInfo) => {
    post<{ uuid: string; url: string }>("/pegasus/api/create/", data).then(
      (res) => {
        if (res.status === 0) {
          message.success("提交成功")
          onSuccess(res.data.uuid)
        } else {
          message.success("提交失败")
        }
      }
    )
  }

  const handleSubmit = () => {
    form
      .validateFields()
      .then((res: FormInfo) => {
        postCreateData(res)
      })
      .catch((e) => {
        // message.error(e)
      })
  }

  return (
    <Drawer
      visible={visible}
      onClose={onClose}
      width={700}
      maskClosable={false}
      title="创建"
      footer={
        <div
          style={{
            textAlign: "right",
          }}
        >
          <Button onClick={handleSubmit} type="primary">
            创建
          </Button>
        </div>
      }
    >
      <Form form={form} layout="vertical">
        <Form.Item
          label="目标页面URL"
          name="url"
          required
          rules={[{ required: true, message: "请输入URL" }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label="超时时间(单位秒)"
          name="timeout"
          required
          rules={[{ required: true, message: "请输入超时时间" }]}
          initialValue={20}
        >
          <InputNumber />
        </Form.Item>
      </Form>
    </Drawer>
  )
}
